package cz.byteworks.sandbox.html5.newsbox.dao.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cz.byteworks.sandbox.html5.newsbox.app.FixedSizeQueue;
import cz.byteworks.sandbox.html5.newsbox.dao.IMessageDAO;
import cz.byteworks.sandbox.html5.newsbox.dao.RepositoryType;
import cz.byteworks.sandbox.html5.newsbox.exception.RepositoryException;
import cz.byteworks.sandbox.html5.newsbox.jms.JmsMessageSender;
import cz.byteworks.sandbox.html5.newsbox.model.NewsMessage;

@Repository
public class JMSMessageDAO implements IMessageDAO {
    
    private RepositoryType repositoryType;
    
    @Autowired(required = true)
    private FixedSizeQueue<NewsMessage> webContainerMessageQueue;
    
    @Autowired
    private JmsMessageSender messageSender;
    
    public JMSMessageDAO() {
        repositoryType = new RepositoryType();
        repositoryType.setTechnicalName("ACTIVE_MQ_JMS_QUEUE");
        repositoryType.setUserFriendlyName("Message queue");
        repositoryType.setUnknownErrorMessage("unknown error occured");
        repositoryType.setUnavailableMessage("service is temporarily unavailable");
    }

    @Override
    public List<NewsMessage> loadNewMessages() throws RepositoryException {
        try {
            List<NewsMessage> messages = new ArrayList<NewsMessage>(Arrays.asList(webContainerMessageQueue.toArray(new NewsMessage[0])));
            return messages;
        }
        catch (Exception e) {
            throw new RepositoryException(getRepositoryType(), e.getMessage(), e);
        }
    }

    @Override
    public RepositoryType getRepositoryType() {
        return repositoryType;
    }

    @Override
    public void sendMessage(NewsMessage message) throws RepositoryException {
        try {
            messageSender.send(message);
        } catch (Exception e) {
            throw new RepositoryException(getRepositoryType(), e.getMessage(), e);
        }
    }

}
